﻿#include "FEPointJunctionDialog.h"
#include "ui_FEPointJunctionDialog.h"

#include "OperatorsInterface/ParaWidgetInterfaceOperator.h"

#include "FITK_Kernel/FITKAppFramework/FITKAppFramework.h"
#include "FITK_Kernel/FITKAppFramework/FITKGlobalData.h"
#include "FITK_Kernel/FITKCore/FITKVec3D.h"
#include "FITK_Component/FITKAcousticsModel/FITKAcousticsDiscModel.h"
#include "FITK_Component/FITKAcousticsModel/FITKFEJunctionPoint.h"
#include "FITK_Component/FITKAcousticsModel/FITKAcousticsFEModel.h"
#include "FITK_Component/FITKAcousticsModel/FITKAbstractFESubSys.h"
#include "FITK_Component/FITKAcousticsModel/FITKAcousticsDiscNodeList.h"

#include <QList>
#include <QMessageBox>
#include <QTableWidgetItem>

#define PointJunction_SubSysPos Qt::UserRole
#define PointJunction_PointPos Qt::UserRole+1

namespace GUI
{
    FEPointJunctionDialog::FEPointJunctionDialog(int dataID, EventOper::ParaWidgetInterfaceOperator * oper, bool isCreate) :
        GUIJunctionDialogBase(dataID, oper, isCreate, FITKAPP->getGlobalData()->getMainWindow())
    {
        _ui = new Ui::FEPointJunctionDialog();
        _ui->setupUi(this);

        if (isCreate == false) {
            _currentDataID = dataID;
        }
        //初始化
        init();
    }

    FEPointJunctionDialog::~FEPointJunctionDialog()
    {
        if (_ui) {
            delete _ui;
            _ui = nullptr;
        }
    }

    void FEPointJunctionDialog::init()
    {
        _ui->tabWidget->tabBar()->hide();
        QStringList connectFEHeader;
        connectFEHeader << QString(tr("Connected FE subsystems"));
        _ui->tableWidget_Connect->setColumnCount(1);
        _ui->tableWidget_Connect->setHorizontalHeaderLabels(connectFEHeader);
        //自适应
        _ui->tableWidget_Connect->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
        //隐藏行表头
        _ui->tableWidget_Connect->verticalHeader()->setVisible(false);

        _ui->label_Image->setPixmap(QPixmap(":/icons/SEA_Junction_Point.png"));
        _ui->checkBox_EnabledJunction->setChecked(true);

        if (_isCreate)
        {
            _ui->tabWidget->setCurrentIndex(0);
            this->InitCreate();
        }
        else
        {
            _ui->tabWidget->setCurrentIndex(1);
            this->InitEdit();
        }
    }

    void FEPointJunctionDialog::setSubsysIDs(QList<QPair<int, int>> subsys)
    {
        if (_FEModel == nullptr) return;
        //FE模型管理器
        Acoustics::FITKAcousticsFESubSysManager* feManager = _FEModel->getFESubSysManager();
        if (!feManager) return;
        //遍历所有子系统
        QList<Acoustics::FITKFEJunPointConStr> connectsFE = {};
        for (QList<QPair<int, int>>::iterator iter = subsys.begin(); iter != subsys.end(); ++iter)
        {
            int subsysID = iter->first, pointID = iter->second;
            Acoustics::FITKAbstractFESubSys* subSysFEData = feManager->getDataByID(subsysID);
            if (!subSysFEData) continue;
            //判断子系统是否被使用
            bool isUseSub = false;
            for (Acoustics::FITKFEJunPointConStr str : connectsFE) {
                if (str._subSysID != subsysID)continue;
                isUseSub = true;
                break;
            }
            if (isUseSub == true)continue;
            //子系统id与点id
            Acoustics::FITKFEJunPointConStr conStr;
            conStr._subSysID = subsysID;
            conStr._pointID = pointID;

            connectsFE.append(conStr);
        }
        //初始化
        this->initTable(connectsFE);
    }

    void FEPointJunctionDialog::setNode(int nodeID)
    {
        this->initWidgetNodeData(nodeID);
    }

    void FEPointJunctionDialog::on_pushButton_Ok_clicked()
    {
        if (_isCreate) {
            if (OKCreate() == false)return;
        }
        else {
            if (OKEdit() == false)return;
        }
        if (_oper) {
            _oper->setArgs(objID_String, _currentDataID);
            _oper->execProfession();
        }
        this->accept();
    }

    void FEPointJunctionDialog::on_pushButton_Cancel_clicked()
    {
        this->reject();
    }

    void FEPointJunctionDialog::InitCreate()
    {
        if (_DiscModel == nullptr && _DiscModel->getJunctionManager() == nullptr)return;
        QString name = "FE Point-0";
        name = _DiscModel->getJunctionManager()->checkName(name);
        _ui->lineEdit_Name->setText(name);
    }

    void FEPointJunctionDialog::InitEdit()
    {
        if (_DiscModel == nullptr && _DiscModel->getJunctionManager() == nullptr)return;
        Acoustics::FITKFEJunctionPoint* junData = dynamic_cast<Acoustics::FITKFEJunctionPoint*>(_DiscModel->getJunctionManager()->getDataByID(_currentDataID));
        if (junData == nullptr)return;
        QString name = junData->getDataObjectName();
        _ui->lineEdit_Name->setText(name);

        setDataToWidget(junData);
    }

    void FEPointJunctionDialog::initTable(QList<Acoustics::FITKFEJunPointConStr> connection)
    {
        if (_FEModel == nullptr && _FEModel->getFESubSysManager() == nullptr) false;
        _ui->tableWidget_Connect->setRowCount(0);
        for (int rowIndex = 0; rowIndex < connection.size(); ++rowIndex) {
            Acoustics::FITKFEJunPointConStr str = connection.at(rowIndex);
            Acoustics::FITKAbstractFESubSys* subSys = _FEModel->getFESubSysManager()->getDataByID(str._subSysID);
            if (subSys == nullptr)continue;
            _ui->tableWidget_Connect->setRowCount(rowIndex + 1);
            QTableWidgetItem* item = new QTableWidgetItem();
            item->setText(subSys->getDataObjectName());
            item->setData(PointJunction_SubSysPos, subSys->getDataObjectID());
            item->setData(PointJunction_PointPos, str._pointID);
            item->setFlags(Qt::ItemIsEnabled);
            _ui->tableWidget_Connect->setItem(rowIndex, 0, item);

            if (rowIndex == 0)
            {
                _ui->lineEdit_Node1ID->setText(QString::number(str._pointID));
                _ui->lineEdit_Node1FESub->setText(subSys->getDataObjectName());
            }
            else if (rowIndex == 1)
            {
                _ui->lineEdit_Node2ID->setText(QString::number(str._pointID));
                _ui->lineEdit_Node2FESub->setText(subSys->getDataObjectName());
            }
        }
    }

    void FEPointJunctionDialog::initWidgetNodeData(int pointID)
    {
        if (_DiscModel == nullptr && _DiscModel->getNodes() == nullptr) return;
        //获取数据
        Core::FITKNode* node = _DiscModel->getNodes()->getNodeByID(pointID);
        if (node == nullptr)return;
        double coor[3]{ 0,0,0 };
        node->getCoor(coor);
        //设置数据到界面
        _ui->lineEdit_NodeID->setText(QString::number(pointID));
        _ui->lineEdit_X->setText(QString::number(coor[0]));
        _ui->lineEdit_Y->setText(QString::number(coor[1]));
        _ui->lineEdit_Z->setText(QString::number(coor[2]));
    }


    bool FEPointJunctionDialog::OKCreate()
    {
        if (_DiscModel == nullptr && _DiscModel->getJunctionManager() == nullptr)return false;
        QString name = _ui->lineEdit_Name->text();
        if (_DiscModel->getJunctionManager()->getDataByName(name)) {
            QMessageBox box(QMessageBox::Warning, "", QString(tr("\"%1\" already exists and cannot be overwritten.")).arg(name), QMessageBox::Ok);
            box.exec();
            return false;
        }

        Acoustics::FITKFEJunctionPoint* junData = new Acoustics::FITKFEJunctionPoint();
        junData->setDataObjectName(name);
        junData->setAutoCreate(false);
        _currentDataID = junData->getDataObjectID();
        //设置界面数据
        getDataFromWidget(junData);
        _DiscModel->getJunctionManager()->appendDataObj(junData);
        return true;
    }

    bool FEPointJunctionDialog::OKEdit()
    {
        if (_DiscModel == nullptr && _DiscModel->getJunctionManager() == nullptr)return false;
        QString name = _ui->lineEdit_Name->text();
        auto junData = dynamic_cast<Acoustics::FITKFEJunctionPoint*>(_DiscModel->getJunctionManager()->getDataByID(_currentDataID));
        if (junData == nullptr)return false;
        //名称重复判断
        if (name != junData->getDataObjectName())
            if (_DiscModel->getJunctionManager()->getDataByName(name)) {
                QMessageBox::warning(this, "", tr("\"%1\" already exists and cannot be overwritten.").arg(name), QMessageBox::Ok);
                return false;
            }
        //设置名称
        junData->setDataObjectName(name);
        //设置界面数据
        getDataFromWidget(junData);
        return true;
    }

    void FEPointJunctionDialog::getDataFromWidget(Acoustics::FITKFEJunctionPoint* data)
    {
        if (data == nullptr)return;
        QList<Acoustics::FITKFEJunPointConStr> conInfoFE;
        //获取关联FE子系统数据
        int conRowCount = _ui->tableWidget_Connect->rowCount();
        for (int i = 0; i < conRowCount; i++) {
            Acoustics::FITKFEJunPointConStr conStr;
            //子系统id与连接点id
            QTableWidgetItem* item = _ui->tableWidget_Connect->item(i, 0);
            if (item) {
                conStr._subSysID = item->data(PointJunction_SubSysPos).toInt();
                conStr._pointID = item->data(PointJunction_PointPos).toInt();
            }
            conInfoFE.append(conStr);
        }
        
        data->replaceConnections(conInfoFE);

        data->setEnabledJunction(_ui->checkBox_EnabledJunction->isChecked());
        int pointID = _ui->lineEdit_NodeID->text().toInt();
        data->setPointID(pointID);
    }

    void FEPointJunctionDialog::setDataToWidget(Acoustics::FITKFEJunctionPoint* data)
    {
        bool isEnable = data->getEnabledJunction();
        _ui->checkBox_EnabledJunction->setChecked(isEnable);

        this->initTable(data->getFEConnections());
        this->initWidgetNodeData(data->getPointID());
    }
}
